import Vue from 'vue'
import VueRouter from 'vue-router'
import VueStore from '@/store' // 主框架的
import { EpMessage as Message } from 'ep-ui'
import { deleteToken } from 'src/utils/auth'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'ep',
    redirect: '/home',
    meta: {
      title: '首页'
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ './login'),
    meta: {
      title: '登陆'
    }
  },
  {
    path: '/chunk/:route',
    name: 'chunk',
    component: () => import(/* webpackChunkName: "chunk" */ './render'),
    meta: {
      title: 'chunk页面',
      chunk: true
    }
  },
  {
    path: '/chunk/:route/:id',
    name: 'chunkMulti',
    component: () => import(/* webpackChunkName: "chunkmulti" */ './render'),
    meta: {
      title: 'chunkd多页面',
      chunk: true,
      multi: true
      // multiKey: 'id',
    }
  },
  {
    path: '/home',
    component: () => import(/* webpackChunkName: "chunk" */ './home.vue'),
    meta: {
      title: '首页'
    }
  }
  // {
  //   path: '*',
  //   name: '404',
  //   component: () => import(/* webpackChunkName: "404" */ '@/views/404.vue')
  // },
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  let userInfo = VueStore.state.app.userInfo
  if (userInfo) {
    // 用户信息已获取
    next()
  } else if (to.path === '/home' || to.path === '/login') {
    next()
  } else {
    // 用户信息未获取
    VueStore.dispatch('app/getUserInfo')
      .then(res => {
        next()
      })
      .catch(err => {
        console.log(err)
        Message({
          type: 'danger',
          message: '获取用户信息失败，请尝试刷新'
        })
        deleteToken()
      })
  }
})

export default router
